<template>
  <el-row :gutter="20">
    <el-col :offset="3" :span="7">
      <h2>热搜榜单</h2>
      <div class="listBig">
        <div
          class="options"
          v-bind:key="index"
          v-for="(item, index) in souData"
        >
          <div class="orders">
            <span>{{ index + 1 }}</span>
          </div>
          <div class="schoolMain">
            <div class="schoolName">
              <!-- <img src="./logo.jpg" /> -->
              <p>{{ item.name }}</p>
            </div>
            <div class="people">
              <p>{{ item.number }}次</p>
            </div>
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="13">
      <div class="grid-content bg-purple">
        <h2>果品分析可视化</h2>
        <div
          class="com_chart"
          id="ref_hot"
          style="height: 500px; width: 100%"
        ></div>
        <div
          class="com_chart"
          id="ref_hot2"
          style="height: 600px; width: 100%"
        ></div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
// @ is an alias to /src

export default {
  name: "Hot",
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([ a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法的邮箱"));
      }
    };
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法的手机号"));
      }
    };
    return {
      // 获取用户的列表参数
      queryInfo: {
        // query: "",
        // 当前页数
        current: 1,
        // 当前每页显示多少条数据
        size: 20,
        userId: window.sessionStorage.getItem("user"),
      },
      // 用户列表数据
      userlist: [],
      total: 0,
      addDialogVisiable: false,
      editDialogVisiable: false,
      // 添加用户的表单数据
      addForm: {
        name: "",
        password: "",
        email: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      // 查询到的用户信息对象
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },

      echartInstance: null,
      echartInstance2: null,
      allData: null,
      titleSize: 0,
      // 当前展示第一分类
      courrentIndex: 0,

      charData: [],
      charData2: [],
      souData: [],
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get(
        `/api/record/list/${this.queryInfo.userId}`,
        {
          params: this.queryInfo,
        }
      );
      if (res.code !== 200) {
        return this.$message.error(res.msg);
      } else {
        this.userlist = res.data.records;
        this.allData = res.data.records;
        // this.total = res.data.total;
      }
      console.log(res);
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagesizes = newPage;
      this.getUserList();
    },
    // 监听switch开关状态的改变
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起用户的网络请求
        const { data: res } = await this.$http.post(
          "/api/user/back",
          this.addForm
        );
        if (res.status !== 200) {
          this.$message.error(res.msg);
        } else {
          this.$message.success(res.msg);
          this.addDialogVisiable = false;
          // 重新获取用户列表
          this.getUserList();
        }
      });
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`/api/user/back/${id}`);
      if (res.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.editForm = res.obj;
      this.editDialogVisiable = true;
    },
    editUserInfo() {
      console.log("修改用户");
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起修改用户的网络请求
        const { data: res } = await this.$http.put(`/api/user/`, {
          id: this.editForm.id,
          email: this.editForm.email,
          name: this.editForm.name,
        });
        if (res.status !== 200) {
          return this.$message.error(res.msg);
        } else {
          this.$message.success(res.msg);
          this.editDialogVisiable = false;
          // 重新获取用户列表
          this.getUserList();
        }
      });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async removeUserById(id) {
      // 弹框询问是否确认删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("/api/user/back/", {
        params: {
          userId: id,
        },
      });
      if (res.status !== 200) {
        return this.$message.error(res.msg);
      } else {
        this.$message.success(res.msg);
        // 重新获取用户列表
        this.getUserList();
      }
    },

    async initChart() {
      this.echartInstance = this.$echarts.init(
        document.getElementById("ref_hot")
      );
      this.echartInstance2 = this.$echarts.init(
        document.getElementById("ref_hot2")
      );

      const initOption = {
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          left: "center",
        },
        color: [
          "#5470c6",
          "#91cc75",
          "#fac858",
          "#ee6666",
          "#73c0de",
          "#3ba272",
          "#fc8452",
          "#9a60b4",
          "#ea7ccc",
        ],
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "40",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: [],
          },
        ],
      };
      const initOption2 = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        color: [
          "#5470c6",
          "#91cc75",
          "#fac858",
          "#ee6666",
          "#73c0de",
          "#3ba272",
          "#fc8452",
          "#9a60b4",
          "#ea7ccc",
        ],
        xAxis: [
          {
            type: "category",
            data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: "直接访问",
            type: "bar",
            barWidth: "60%",
            data: [10, 52, 200, 334, 390, 330, 220],
          },
        ],
      };
      this.echartInstance.setOption(initOption);
      this.echartInstance2.setOption(initOption2);
    },
    async getData() {
      const { data: res } = await this.$http.get(`/api/record/top-search`);
      console.log(res);
      this.allData = res.data;
      this.souData = res.data;

      this.charData = this.allData.map((i) => {
        return {
          name: i.name,
          value: i.number,
        };
      });
      this.charData2 = this.allData.map((i) => {
        return i.number;
      });

      this.upData();
    },
    upData() {
      // 处理数据
      const dataOption = {
        series: [
          {
            data: this.charData,
          },
        ],
      };
      const dataOption2 = {
        series: [
          {
            data: this.charData2,
          },
        ],
        legend: {
          data: this.charData2,
        },
        xAxis: {
          data: this.allData.map((i) => {
            return i.name;
          }),
        },
      };

      this.echartInstance.setOption(dataOption);
      this.echartInstance2.setOption(dataOption2);
    },
  },
  mounted() {
    this.initChart();
    this.getData();
    window.addEventListener("resize", this.screenAdapter);
    this.screenAdapter();
  },
  destroyed() {
    window.removeEventListener("resize", this.screenAdapter);
  },
};
</script>
<style scoped>
.el-row {
  margin: 50px auto;
  max-width: 1300px;
}
p {
  /* font-size: 12px; */
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.listBig {
  width: 268px;
  height: 400px;
  border: 1px dotted #ccc;
}

.listBig .options:nth-child(1) {
  font-size: 1.3em;
  padding: 8px 0 8px;
  font-weight: 600;
  font-family: '黑体';
  color: #fff;
  border-bottom: 0;
  background-color: #66cc33;
}

.listBig .options:nth-child(1) p,
.listBig .options:nth-child(1) span {
  line-height: 50px;
}

.listBig .options:nth-child(2) {
  font-size: 1.03em;
  color: #fff;
  background-color: #9bd37f;
}
.listBig .options:nth-child(3) {
  font-size: 1em;
  color: #fff;
  background-color: #b4dd9f;
}

.listBig .options {
  width: 100%;
  height: 33px;
  line-height: 33px;
  /*border:1px solid red;*/
  padding-bottom: 5px;
  position: relative;
}

.listBig .options .orders {
  width: 19px;
  height: 28px;

  position: absolute;
  left: 8px;
  top: 0;
}

.schoolMain {
  height: 100%;
  width: 223px;
  position: absolute;
  left: 28px;
  top: 0;
  right: 22px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
}

.schoolName {
  width: 150px;
  height: 28px;
  position: absolute;
  left: 0;
  top: 0;
}

.schoolName img {
  height: 100%;
  width: 28px;
  float: left;
}

.schoolName p {
  float: left;
  margin-left: 7px;
}

.options .people {
  width: 73px;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
  text-align: right;
}
</style>
